﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using FunctionalCLR.Core;

namespace FunctionalCLR.Shell.Databasing
{
    public class SqlSelectNode : FuncNode
    {
        public SqlSelectNode()
            : base("select")
        {
        }

        public override object Evaluate()
        {
            int length = Parameters.Count;
            if (length < 1)
            {
                throw new ArgumentException(
                    "usage: select(query, conn)");
            }

            string query = Convert.ToString(
                Parameters[length - 1].Evaluate());
            SqlConnection conn = Parameters[length - 2].Evaluate() as SqlConnection;

            DataTable dt = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
            adapter.Fill(dt);

            return dt;
        }
    }
}
